package br.com.gbvbahia.mybooks.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import br.com.gbvbahia.commons.dao.InterfaceDAO;
import br.com.gbvbahia.mybooks.dao.contract.DB;
import br.com.gbvbahia.mybooks.modelos.EditoraVO;

public class EditoraDAO extends InterfaceDAO<EditoraVO, String> {
	public static final String EDITORA_TABLE_NAME = "editoras";
	public static final String[] columns = { "id", "nome", "data_alteracao",
			"sincronizado" };

	public EditoraDAO(Context ctx) {
		super(new DB(ctx));
	}

	@Override
	protected String getColumnIdName() {
		return columns[0];
	}

	@Override
	protected String getTableName() {
		return EDITORA_TABLE_NAME;
	}

	@Override
	protected String[] getColumNames() {
		return columns;
	}

	@Override
	protected String getColumnOrderDefault() {
		return columns[1];
	}

	@Override
	protected EditoraVO getFromCursor(Cursor cursor) {
		EditoraVO toReturn = new EditoraVO();
		toReturn.setId(cursor.getString(cursor.getColumnIndex(columns[0])));
		toReturn.setNome(cursor.getString(cursor.getColumnIndex(columns[1])));
		toReturn.setDataAlteracao(Long.parseLong(cursor.getString(cursor
				.getColumnIndex(columns[2]))));
		toReturn.setSincronizado(cursor.getInt(cursor
				.getColumnIndex(columns[3])));
		return toReturn;
	}

	@Override
	protected void populateContentValues(ContentValues cv, EditoraVO t) {
		cv.put(columns[0], t.getId());
		cv.put(columns[1], t.getNome());
		cv.put(columns[2], Long.toString(t.getDataAlteracao()));
		cv.put(columns[3], t.getSincronizado());
	}

	/**
	 * Retorna a editora por nome.
	 * 
	 * @param name
	 * @return
	 */
	public EditoraVO getEditoraByName(String name) {
		SQLiteDatabase db = null;
		Cursor cursor = null;
		try {
			db = getDataBase();
			cursor = db.query(EDITORA_TABLE_NAME, columns, columns[1] + "=?",
					new String[] { name }, null, null, null);
			EditoraVO toReturn = null;
			if (cursor.moveToFirst()) {
				toReturn = getFromCursor(cursor);
			}
			return toReturn;
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
	}

	/**
	 * Busca todos os nomes das editoras distintos e ordenados em uma lista.
	 * 
	 * @return
	 */
	public List<String> buscarEditoras() {
		Cursor cursor = null;
		try {
			List<String> toReturn = new ArrayList<String>();
			cursor = getDataBase().query(true, EDITORA_TABLE_NAME,
					new String[] { columns[1] }, null, null, null, null,
					columns[1], null);
			while (cursor.moveToNext()) {
				toReturn.add(cursor.getString(0));
			}
			return toReturn;
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
	}

}
